import decompress from 'decompress'
import os from 'os'
import fs from 'fs';
import {Extractor} from '../../src/tool/extract';
import * as sinon from 'sinon';
import {expect} from 'chai'

describe('extractor extract test case', () => {
    let mkdirSyncStub: sinon.SinonStub;
    let decompressFuncStub: sinon.SinonStub;
    let extractor: Extractor

    beforeEach(() => {
        mkdirSyncStub = sinon.stub(fs, 'mkdirSync');
        decompressFuncStub = sinon.stub();
        extractor = new Extractor(decompressFuncStub)
    });

    afterEach(() => {
        sinon.restore();
    });

    it('should extract the file without specified directory', async () => {
        const filePath = 'path/to/archive.tar.gz';
        const tmpDir = 'path/to/temp';
        sinon.stub(os, 'tmpdir').returns(tmpDir);

        const extractedPath = await extractor.extract(filePath)
        expect(extractedPath).to.contains("path/to/temp")

        sinon.assert.calledOnce(mkdirSyncStub)
    });

    it('should extract the file to the specified directory', async () => {
        const filePath = 'path/to/archive.zip';
        const destDir = 'path/to/destination';

        const extractedPath = await extractor.extract(filePath, destDir);
        expect(extractedPath).to.equals(destDir)

        sinon.assert.calledOnceWithExactly(mkdirSyncStub, destDir, {recursive: true});
    });

    it('should use the provided decompress options if provided', async () => {
        const filePath = 'path/to/archive.zip';
        const destDir = 'path/to/destination';
        const decompressOptions: decompress.DecompressOptions = {
            strip: 1,
        }

        const extractedPath = await extractor.extract(filePath, destDir, decompressOptions);
        expect(extractedPath).to.equals(destDir)

        sinon.assert.calledOnceWithExactly(mkdirSyncStub, destDir, {recursive: true});
        sinon.assert.calledOnceWithExactly(decompressFuncStub, filePath, destDir, {strip: 1})
    });
})
